import { request } from '../request';

interface dictItem {
    itemText: string;
    itemValue: string;
}

// 缓存字典数据
const dictCache = new Map<string, Array<dictItem>>();

// interface Dict {
//     records: Array<any>
// }

export async function getDict(dictCode: String) {
    const { error, success } = await request.get<any>(`/sys/dict/list?dictCode=${dictCode}`, {}, {
        useErrMsg: true
    });
    const id = success?.records[0]?.id

    if (!error && id) {
        const { error, success } = await request.get<any>(`/sys/dictItem/list?dictId=${id}`, {}, {
            useErrMsg: true
        });

        if (!error && success?.records) return success?.records as Array<dictItem>
    }
}

// 带缓存的字典获取方法
export async function getDictWithCache(dictCode: string): Promise<Array<dictItem> | null> {
    // 检查缓存中是否已有数据
    if (dictCache.has(dictCode)) {
        return dictCache.get(dictCode) || null;
    }

    try {
        // 获取字典数据
        const { error, success } = await request.get<any>(`/sys/dict/list?dictCode=${dictCode}`, {}, {
            useErrMsg: false // 不显示错误消息，避免频繁请求时的错误提示
        });
        
        const id = success?.records[0]?.id;

        if (!error && id) {
            const { error: itemError, success: itemSuccess } = await request.get<any>(`/sys/dictItem/list?dictId=${id}`, {}, {
                useErrMsg: false
            });

            if (!itemError && itemSuccess?.records) {
                const dictData = itemSuccess.records as Array<dictItem>;
                // 将数据存入缓存
                dictCache.set(dictCode, dictData);
                return dictData;
            }
        }
        
        return null;
    } catch (error) {
        console.error(`获取字典数据失败: ${dictCode}`, error);
        return null;
    }
}

// 清除字典缓存
export function clearDictCache(dictCode?: string) {
    if (dictCode) {
        dictCache.delete(dictCode);
    } else {
        dictCache.clear();
    }
}

// 预加载字典数据
export async function preloadDict(dictCodes: string[]) {
    const promises = dictCodes.map(code => getDictWithCache(code));
    await Promise.all(promises);
}
